// pages/student/replay/replay.js
import { courses } from '../../../utils/mockData.js'

Page({
  data: {
    courseId: null,
    lessonId: null,
    course: null,
    currentLesson: null,
    currentChapter: null,
    chapters: [],
    videoContext: null,
    // 播放器状态
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    progress: 0,
    // UI控制
    showChapterList: false,
    expandedChapters: [],
    // 学习记录
    studyStartTime: null,
    totalStudyTime: 0,
    // 播放速度
    playbackRate: 1.0,
    showSpeedMenu: false,
    speedOptions: [0.5, 0.75, 1.0, 1.25, 1.5, 2.0]
  },

  onLoad(options) {
    const { courseId, lessonId } = options
    
    if (courseId) {
      this.setData({ courseId: parseInt(courseId) })
      this.loadCourseData()
    }
    
    if (lessonId) {
      this.setData({ lessonId: parseInt(lessonId) })
    }
  },

  onReady() {
    // 获取视频上下文
    this.videoContext = wx.createVideoContext('courseVideo', this)
  },

  onShow() {
    // 记录学习开始时间
    this.setData({
      studyStartTime: Date.now()
    })
  },

  onHide() {
    // 保存学习记录
    this.saveStudyRecord()
  },

  onUnload() {
    // 保存学习记录
    this.saveStudyRecord()
  },

  // 加载课程数据
  loadCourseData() {
    const course = courses.find(c => c.id === this.data.courseId)
    if (!course) {
      wx.showToast({
        title: '课程不存在',
        icon: 'none'
      })
      return
    }

    // 处理章节数据,添加完成状态
    const chaptersWithStatus = course.chapters.map(chapter => ({
      ...chapter,
      lessons: chapter.lessons.map(lesson => ({
        ...lesson,
        isCompleted: false, // 实际应该从后端获取
        watchProgress: 0 // 观看进度
      }))
    }))

    this.setData({
      course,
      chapters: chaptersWithStatus
    })

    // 如果指定了课时,播放该课时;否则播放第一个课时
    if (this.data.lessonId) {
      this.findAndPlayLesson(this.data.lessonId)
    } else if (chaptersWithStatus.length > 0 && chaptersWithStatus[0].lessons.length > 0) {
      const firstLesson = chaptersWithStatus[0].lessons[0]
      this.playSpecificLesson(firstLesson, chaptersWithStatus[0])
    }
  },

  // 查找并播放指定课时
  findAndPlayLesson(lessonId) {
    const { chapters } = this.data
    for (const chapter of chapters) {
      const lesson = chapter.lessons.find(l => l.id === lessonId)
      if (lesson) {
        this.playSpecificLesson(lesson, chapter)
        return
      }
    }
  },

  // 播放指定课时
  playSpecificLesson(lesson, chapter) {
    // 检查是否需要权限
    if (!lesson.is_free && !this.checkEnrollment()) {
      wx.showModal({
        title: '提示',
        content: '该课时需要报名后才能观看',
        confirmText: '去报名',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
      return
    }

    this.setData({
      currentLesson: lesson,
      currentChapter: chapter,
      lessonId: lesson.id
    })

    // 重置播放状态
    if (this.videoContext) {
      this.videoContext.seek(0)
    }
  },

  // 检查是否已报名(模拟)
  checkEnrollment() {
    // 实际应该检查用户的选课记录
    return true
  },

  // 切换课时
  onLessonTap(e) {
    const { lesson, chapter } = e.currentTarget.dataset
    this.saveStudyRecord() // 保存当前课时的学习记录
    this.playSpecificLesson(lesson, chapter)
    this.setData({ showChapterList: false })
  },

  // 视频播放事件
  onVideoPlay() {
    this.setData({ 
      isPlaying: true,
      studyStartTime: Date.now()
    })
  },

  // 视频暂停事件
  onVideoPause() {
    this.setData({ isPlaying: false })
    this.saveStudyRecord()
  },

  // 视频结束事件
  onVideoEnded() {
    this.setData({ isPlaying: false })
    this.saveStudyRecord()
    
    // 标记当前课时为已完成
    this.markLessonCompleted()
    
    // 自动播放下一课时
    this.playNextLesson()
  },

  // 时间更新事件
  onTimeUpdate(e) {
    const { currentTime, duration } = e.detail
    const progress = duration > 0 ? (currentTime / duration * 100).toFixed(1) : 0
    
    this.setData({
      currentTime,
      duration,
      progress
    })
  },

  // 视频错误事件
  onVideoError(e) {
    console.error('视频播放错误', e)
    wx.showToast({
      title: '视频加载失败',
      icon: 'none'
    })
  },

  // 播放/暂停控制
  togglePlay() {
    if (this.data.isPlaying) {
      this.videoContext.pause()
    } else {
      this.videoContext.play()
    }
  },

  // 播放下一课时
  playNextLesson() {
    const { chapters, currentChapter, currentLesson } = this.data
    
    if (!currentChapter || !currentLesson) {
      wx.showToast({
        title: '请先选择课时',
        icon: 'none'
      })
      return
    }
    
    // 在当前章节中查找下一课时
    const currentChapterData = chapters.find(c => c.id === currentChapter.id)
    const currentLessonIndex = currentChapterData.lessons.findIndex(l => l.id === currentLesson.id)
    
    if (currentLessonIndex < currentChapterData.lessons.length - 1) {
      // 播放当前章节的下一课时
      const nextLesson = currentChapterData.lessons[currentLessonIndex + 1]
      this.playSpecificLesson(nextLesson, currentChapter)
    } else {
      // 查找下一章节
      const currentChapterIndex = chapters.findIndex(c => c.id === currentChapter.id)
      if (currentChapterIndex < chapters.length - 1) {
        const nextChapter = chapters[currentChapterIndex + 1]
        if (nextChapter.lessons.length > 0) {
          this.playSpecificLesson(nextChapter.lessons[0], nextChapter)
        }
      } else {
        wx.showToast({
          title: '已完成所有课时',
          icon: 'success'
        })
      }
    }
  },

  // 播放上一课时
  playPrevLesson() {
    const { chapters, currentChapter, currentLesson } = this.data
    
    if (!currentChapter || !currentLesson) {
      wx.showToast({
        title: '请先选择课时',
        icon: 'none'
      })
      return
    }
    
    // 在当前章节中查找上一课时
    const currentChapterData = chapters.find(c => c.id === currentChapter.id)
    const currentLessonIndex = currentChapterData.lessons.findIndex(l => l.id === currentLesson.id)
    
    if (currentLessonIndex > 0) {
      // 播放当前章节的上一课时
      const prevLesson = currentChapterData.lessons[currentLessonIndex - 1]
      this.playSpecificLesson(prevLesson, currentChapter)
    } else {
      // 查找上一章节
      const currentChapterIndex = chapters.findIndex(c => c.id === currentChapter.id)
      if (currentChapterIndex > 0) {
        const prevChapter = chapters[currentChapterIndex - 1]
        if (prevChapter.lessons.length > 0) {
          const lastLesson = prevChapter.lessons[prevChapter.lessons.length - 1]
          this.playSpecificLesson(lastLesson, prevChapter)
        }
      } else {
        wx.showToast({
          title: '已是第一课时',
          icon: 'none'
        })
      }
    }
  },

  // 标记课时为已完成
  markLessonCompleted() {
    const { chapters, currentLesson } = this.data
    const updatedChapters = chapters.map(chapter => ({
      ...chapter,
      lessons: chapter.lessons.map(lesson => 
        lesson.id === currentLesson.id 
          ? { ...lesson, isCompleted: true, watchProgress: 100 }
          : lesson
      )
    }))
    
    this.setData({ chapters: updatedChapters })
    
    // 实际应该调用API保存到后端
    console.log('课时已完成', currentLesson.id)
  },

  // 保存学习记录
  saveStudyRecord() {
    const { studyStartTime, currentLesson, currentTime } = this.data
    if (!studyStartTime || !currentLesson) return
    
    const studyDuration = Math.floor((Date.now() - studyStartTime) / 1000)
    if (studyDuration < 1) return
    
    // 实际应该调用API保存到study_records表
    console.log('保存学习记录', {
      lesson_id: currentLesson.id,
      study_duration: studyDuration,
      current_time: currentTime
    })
    
    // 重置开始时间
    this.setData({
      studyStartTime: Date.now(),
      totalStudyTime: this.data.totalStudyTime + studyDuration
    })
  },

  // 切换章节列表显示
  toggleChapterList() {
    this.setData({
      showChapterList: !this.data.showChapterList
    })
  },

  // 展开/收起章节
  toggleChapter(e) {
    const chapterId = e.currentTarget.dataset.id
    const { expandedChapters } = this.data
    const index = expandedChapters.indexOf(chapterId)
    
    if (index > -1) {
      expandedChapters.splice(index, 1)
    } else {
      expandedChapters.push(chapterId)
    }
    
    this.setData({ expandedChapters: [...expandedChapters] })
  },

  // 切换播放速度
  toggleSpeedMenu() {
    this.setData({
      showSpeedMenu: !this.data.showSpeedMenu
    })
  },

  // 选择播放速度
  selectSpeed(e) {
    const rate = e.currentTarget.dataset.rate
    this.setData({
      playbackRate: rate,
      showSpeedMenu: false
    })
    this.videoContext.playbackRate(rate)
    wx.showToast({
      title: `${rate}x 倍速播放`,
      icon: 'none'
    })
  },

  // 返回上一页
  goBack() {
    this.saveStudyRecord()
    wx.navigateBack()
  },

  // 格式化时间显示
  formatTime(seconds) {
    if (!seconds || isNaN(seconds)) return '00:00'
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
})
